﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// RectTransfor 类扩展
/// </summary>
public static class RectTransformExtension
{

    public static void SetAnchoredPositionX(this RectTransform rectTransform, float x)
    {
        Vector2 anchoredPosition = rectTransform.anchoredPosition;
        anchoredPosition.x = x;
        rectTransform.anchoredPosition = anchoredPosition;
    }

    public static void SetAnchoredPositionY(this RectTransform rectTransform, float y)
    {
        Vector2 anchoredPosition = rectTransform.anchoredPosition;
        anchoredPosition.y = y;
        rectTransform.anchoredPosition = anchoredPosition;
    }

    public static void SetSizeDeltaX(this RectTransform rectTransform, float x)
    {
        Vector2 sizeDelta = rectTransform.sizeDelta;
        sizeDelta.x = x;
        rectTransform.sizeDelta = sizeDelta;
    }

    public static void SetSizeDeltaY(this RectTransform rectTransform, float y)
    {
        Vector2 sizeDelta = rectTransform.sizeDelta;
        sizeDelta.y = y;
        rectTransform.sizeDelta = sizeDelta;
    }

    public static Rect Rect2ScreenPos(this RectTransform rt, Camera cam = null)
    {
        Vector3[] corners = new Vector3[4];
        rt.GetWorldCorners(corners);
        Vector2 v0 = RectTransformUtility.WorldToScreenPoint(cam, corners[0]);
        Vector2 v1 = RectTransformUtility.WorldToScreenPoint(cam, corners[2]);
        Rect rect = new Rect(v0, v1 - v0);
        return rect;
    }

    public static void Copy(this RectTransform source, RectTransform clone)
    {
        clone.anchorMin = source.anchorMin;
        clone.anchorMax = source.anchorMax;
        clone.pivot = source.pivot;

        clone.localPosition = source.localPosition;
        clone.localRotation = source.localRotation;
        clone.localScale = source.localScale;
        clone.anchoredPosition = source.anchoredPosition;
        clone.sizeDelta = source.sizeDelta;
    }

    public static RectTransform CloneNew(this RectTransform source)
    {
        var go = new GameObject($"{source.gameObject.name}_Clone", typeof(RectTransform));
        var ret = go.GetComponent<RectTransform>();
        ret.SetParent(source.parent, false);
        source.Copy(ret);
        return ret;
    }

}
